package com.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.exception.ConditionException;

import java.util.Calendar;
import java.util.Date;

public class TokenUtil {

    private static final String ISSUER = "签发者";

    /**
     * 生成短时令牌 (token)
     */
    public static String generateToken(Long userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.SECOND, 6000); // 过期时间为600s=10分钟，100分钟后token会过期
        String token = JWT.create().
                withKeyId(String.valueOf(userId))  //关键词userId
                .withIssuer(ISSUER) //签发者
                .withExpiresAt(calendar.getTime()) //设置过期时间
                .sign(algorithm);  //设置加密算法
        return token;
    }

    /**
     * 验证令牌 (token)，返回 userId
     */
    public static Long verifyToken(String token) {
        Algorithm algorithm;
        try {
            algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
            //jwt验证类
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            String userId = jwt.getKeyId();
            return Long.valueOf(userId);
        } catch (TokenExpiredException e) {
            throw new ConditionException("401", "token过期！");
        } catch (Exception e) {
            throw new ConditionException("401", "非法用户token");
        }
    }

    /**
     * 生成长时令牌
     */
    public static String generateRefreshToken(Long userId) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, 7); //7天
        String token = JWT.create().
                withKeyId(String.valueOf(userId))  //关键词userId
                .withIssuer(ISSUER) //签发者
                .withExpiresAt(calendar.getTime()) //设置过期时间
                .sign(algorithm);  //设置加密算法
        return token;
    }
}
